package com.cskaoyan.typehandler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


@MappedTypes(String[].class)  // 映射的Java类型
@MappedJdbcTypes(JdbcType.VARCHAR)  // 映射的数据库类型
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {  // extends TypeHandler 【也可以继承该类】

    ObjectMapper objectMapper = new ObjectMapper();


    /**
     * @param index    参数序号，第几个参数【第一个参数序号为1
     * @param strings 为预编译sql语句提供的参数
     * @throws SQLException
     */
    // 控制输入映射
    @SneakyThrows
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int index, String[] strings, JdbcType jdbcType) throws SQLException {
        // String[] → String 【goods表的gallery】
        String value = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(index, value);  // JDBC的代码
    }

    // 输出映射
    @SneakyThrows
    @Override
    public String[] getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        // String → String[] 【goods表的gallery】
        String result = resultSet.getString(columnName);

        return transfer(result);
    }

    // 输出映射
    @SneakyThrows
    @Override
    public String[] getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);

        return transfer(result);
    }

    // 输出映射
    @SneakyThrows
    @Override
    public String[] getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);

        return transfer(result);
    }

    private String[] transfer(String result) throws JsonProcessingException {

        if (null == result || "".equals(result))  // 既不为空，也不会空串
            return new String[0];

        String[] strings = new String[0];

        strings = objectMapper.readValue(result, String[].class);
        return strings;
    }
}
